package cn.dqy.gotanserver.code;

import cn.dqy.gotanserver.dto.GoTanInet;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ReplayingDecoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.List;

public class GoTanDtoDecode extends ReplayingDecoder<Void> {
    static Logger logger = LoggerFactory.getLogger(GoTanDtoDecode.class);
    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
        logger.info("开始解码");
        int packLen = in.readInt();
//        packLen= Integer.reverseBytes(packLen); 统一由客户端保证传值正确
        logger.info("packLen={}",packLen);

        ByteBuf byteBuf = in.readBytes(packLen);
        byte[] data=new byte[packLen];
        byteBuf.readBytes(data);

        //data 序列化为 GoTanInet
        //data 结构 {[备注字节长度] [备注byte] [图片字节长度] [图片byte]}
        GoTanInet goTanInet = byteToCoTanInet(data);
        out.add(goTanInet);
        logger.info("解码完毕");
    }

    //字节转化为对象 反序列化
    public GoTanInet byteToCoTanInet(byte[] bytes){
        GoTanInet goTanInet=new GoTanInet();
        String[] inetFiedArr=new String[]{"val","pic"};
        int start=0; int index=0;

        do {
            byte[] lenBytes = Arrays.copyOfRange(bytes, start, start + 4); //读取一个int
            int len = CodeUtils.bytesToIntBigEndian(lenBytes);
            byte[] dataytes = Arrays.copyOfRange(bytes, start + 4, start + 4 + len);

            String name = inetFiedArr[index];
            Field f1 = GoTanInet.fieldMap.get(name);    //数据长度
            Field f2 = GoTanInet.fieldMap.get(name + "_data");  //数据字节数组
            try {
                f1.set(goTanInet, len);
                f2.set(goTanInet, dataytes);
            }catch (Exception e){
                logger.error("反射设置字段失败，原因"+e);
            }
            start = start + 4 + len;
            index++;
        }while (start<bytes.length);

        return goTanInet;
    }
}
